<template>
  <div>
    <BasicTable @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="getActions(record)"
            :dropDownActions="[
              {
                label: '设备流转记录',
                tooltip: '设备流转记录',
                onClick: handleAllocationRecord.bind(null, record),
              },
              {
                label: '删除设备',
                tooltip: '删除设备',
                onClick: handleDel.bind(null, record),
              },
            ]"
          >
            <template #more>
              <Button type="link">更多</Button>
            </template>
          </TableAction>
        </template>
      </template>
      <template #toolbar>
        <div class="flex-warp">
          <a-button type="primary" @click="handleAdd('add', {})">添加设备</a-button>
          <span class="desc"
            >设备总计{{ total }}台，已分配<span style="color: #52c41a">{{ assigned }}</span
            >台，未分配<span style="color: red">{{ undistributed }}</span
            >台
          </span>
        </div>
      </template>
    </BasicTable>

    <!-- 设备新增、编辑弹窗 -->
    <AddedModal @register="register" @reload="reload" />

    <!-- 设备分配弹窗 -->
    <AllocationModal @register="registerAllocation" @reload="reload" />

    <!-- 设备回收弹窗 -->
    <RecoveryModal @register="registerRecovery" @reload="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, ActionItem } from '@/components/Table';
  import AddedModal from './modal/added.vue';
  import AllocationModal from './modal/allocation.vue';
  import RecoveryModal from './modal/recovery.vue';

  import { DeviceList, DeviceDelete, DeviceStatistics } from '@/api/device/deviceList';
  import { IDeviceListResult } from '@/api/device/deviceList/type';
  import { list } from '@/api/institution/list';
  import { getBasicColumns } from './tableData';
  import Dictionary from '@/utils/dictionary';
  import { useModal } from '@/components/Modal';
  import { Modal, Button } from 'ant-design-vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { ref } from 'vue';
  import { DispenseStatusEnum } from '@/enums/device';
  import { useRouter } from 'vue-router';

  const dicts = Dictionary.getLocalMulti([
    'rateType',
    'merchantStatus',
    'terimalStatus',
    'dispenseStatus',
    'dispenseType',
  ]);

  const { createMessage } = useMessage();
  const total = ref(0); //设备总数量
  const assigned = ref(0); //已分配数量
  const undistributed = ref(0); //未分配数量

  const router = useRouter();

  function getStatistics() {
    DeviceStatistics().then((res) => {
      assigned.value = res.isDispenseNum;
      undistributed.value = res.noDispenseNum;
    });
  }
  getStatistics();


  const [registerTable, { reload, getRawDataSource }] = useTable({
    title: '',
    api: DeviceList,
    columns: getBasicColumns(),
    rowKey: 'id',
    useSearchForm: true,
    formConfig: {
      labelWidth: 100,
      schemas: [
        {
          field: `printerNo`,
          label: `设备编号`,
          component: 'Input',
          colProps: {
            span: 4,
          },
        },
        {
          field: `terimalStatus`,
          label: `设备状态`,
          component: 'Select',
          colProps: {
            span: 4,
          },
          componentProps: {
            options: dicts.terimalStatus.map((item) => {
              return {
                label: item.dictLabel,
                value: item.dictValue,
                key: item.dictValue,
              };
            }),
          },
        },
        {
          field: `dispenseType`,
          label: `分配方式`,
          component: 'Select',
          colProps: {
            span: 4,
          },
          componentProps: {
            options: dicts.dispenseType.map((item) => {
              return {
                label: item.dictLabel,
                value: item.dictValue,
                key: item.dictValue,
              };
            }),
          },
        },
        {
          field: `dispenseStatus`,
          label: `分配状态`,
          component: 'Select',
          colProps: {
            span: 4,
          },
          componentProps: {
            options: dicts.dispenseStatus.map((item) => {
              return {
                label: item.dictLabel,
                value: item.dictValue,
                key: item.dictValue,
              };
            }),
          },
        },
        {
          field: `tenantId`,
          label: `分配机构`,
          component: 'ApiSelect',
          colProps: {
            span: 4,
          },
          componentProps: {
            api: list,
            params: { current: 1, size: 10000 },
            labelField: 'orgName',
            valueField: 'tenantId',
            showSearch: true,
            filterOption: (input: string, option: any) => {
              return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
            },
          },
        },
      ],
    },
    showTableSetting: true,
    tableSetting: { fullScreen: true },
    showIndexColumn: true,
    clickToRowSelect: false,
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
    },
    afterFetch: (data: IDeviceListResult[]) => {
      let resData = getRawDataSource();
      total.value = resData.total;
      return data.map((item) => {
        return {
          ...item,
          terimalStatusText: dicts.terimalStatus.find((v) => v.dictValue == item.terimalStatus)
            ?.dictLabel,
          dispenseStatusText: dicts.dispenseStatus.find((v) => v.dictValue == item.dispenseStatus)
            ?.dictLabel,
          dispenseTypeText: dicts.dispenseType.find((v) => v.dictValue == item.dispenseType)
            ?.dictLabel,
          orgName: item.orgName || '平台',
        };
      });
    },
  });

  const getActions = (record: IDeviceListResult) => {
    let actions: ActionItem[] = [];
    if (record.dispenseStatus === DispenseStatusEnum.ASSIGNED) {
      actions.push({
        label: '回收',
        tooltip: '回收',
        onClick: handleRecovery.bind(null, record),
      });
    } else {
      actions.push({
        label: '分配',
        tooltip: '分配',
        onClick: handleAllocation.bind(null, record),
      });
    }

    actions.push({
      label: '编辑',
      tooltip: '编辑',
      onClick: handleAdd.bind(null, 'edit', record),
    });
    return actions;
  };

  const [register, { openModal }] = useModal();

  function handleAdd(type: string, row: any) {
    openModal(true, {
      type,
      row,
    });
  }

  async function handleDel(row: IDeviceListResult) {
    Modal.confirm({
      title: '提示',
      content: '该操作将删除该设备',
      onOk: async () => {
        await DeviceDelete({ id: row.id });
        createMessage.success('删除成功！');
        reload();
      },
    });
  }

  const [registerAllocation, { openModal: openAllocationModal }] = useModal();
  const handleAllocation = (row: IDeviceListResult) => {
    openAllocationModal(true, {
      row,
    });
  };

  const [registerRecovery, { openModal: openRecoveryModal }] = useModal();
  const handleRecovery = (row: IDeviceListResult) => {
    openRecoveryModal(true, {
      row,
    });
  };

  function handleAllocationRecord(row: IDeviceListResult) {
    router.push({
      path: '/device/allocationList',
      query: { printerNo: row.printerNo },
    });
  }
</script>

<style lang="less" scoped>
  .flex-warp {
    flex: 1;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .desc {
      margin-left: 10px;
    }
  }
</style>
